package com.up.vms.interfaces.rest.security;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.util.StringUtils;
import com.up.vms.infrastructure.mvc.RespCode;
import com.up.vms.infrastructure.mvc.ReturnCode;
import com.up.vms.interfaces.rest.response.CommonResponse;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * <p>
 * 自定义失败类
 * </p>
 *
 */
@Slf4j
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        HttpSession httpSession = request.getSession();
        CommonResponse systemResponseMsg = new CommonResponse();

        // 用户名为空
        if (StringUtils.isEmpty(username)) {
            SecurityContextHolder.getContext().setAuthentication(null);
            RespCode responseCode = new RespCode(ReturnCode.SYSTEM_LOGIN_NULL);
            systemResponseMsg.setRespCode(responseCode);
        }

        // 密码不能为空
        if (StringUtils.isEmpty(password)) {
            SecurityContextHolder.getContext().setAuthentication(null);
            RespCode responseCode = new RespCode(ReturnCode.SYSTEM_LOGIN_NULL);
            systemResponseMsg.setRespCode(responseCode);
        }

        // 处理用户名、密码错误的情况
        if (exception instanceof BadCredentialsException) {
            httpSession.setAttribute("message", "用户名或密码错误");
            RespCode responseCode = new RespCode(ReturnCode.SYSTEM_LOGIN_FAILED);
            systemResponseMsg.setRespCode(responseCode);
        }

        if (exception != null) {
            log.info("用户登录异常：{}", ExceptionUtils.getMessage(exception));
            RespCode responseCode = new RespCode(ReturnCode.SYSTEM_LOGIN_FAILED);
            systemResponseMsg.setRespCode(responseCode);
        }

        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(systemResponseMsg));
    }
}
